package com.ruoyi.drone.controller;

import java.util.Date;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import com.ruoyi.drone.domain.DroneOrganization;
import com.ruoyi.drone.domain.DroneTask;
import com.ruoyi.drone.mapper.DroneOrganizationMapper;
import com.ruoyi.drone.service.IDroneTaskService;
import com.ruoyi.drone.service.IDroneTaskCategoryService;
import com.ruoyi.drone.domain.DroneTaskCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

/**
 * 简化版任务发布Controller - 用于测试
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/drone/taskSimple")
public class DroneTaskSimpleController extends BaseController
{
    @Autowired
    private IDroneTaskService droneTaskService;

    @Autowired
    private IDroneTaskCategoryService droneTaskCategoryService;

    @Autowired
    private DroneOrganizationMapper droneOrganizationMapper;

    /**
     * 获取任务分类列表（无需认证）
     */
    @GetMapping("/categories")
    public AjaxResult getCategories()
    {
        List<DroneTaskCategory> categories = droneTaskCategoryService.selectAllEnabledCategories();
        return success(categories);
    }

    /**
     * 简化版发布任务（需要认证）
     */
    @Log(title = "简化版任务发布", businessType = BusinessType.INSERT)
    @PostMapping("/publish")
    public AjaxResult publishTask(HttpServletRequest request, @RequestBody SimpleTaskRequest taskRequest)
    {
        try {
            Long userId = (Long) request.getAttribute("userId");
            String phone = (String) request.getAttribute("phone");
            
            System.out.println("Controller - userId: " + userId + ", phone: " + phone);
            
            System.out.println("Controller - 接收到的taskRequest: " + taskRequest);
            System.out.println("Controller - taskImages: " + taskRequest.getTaskImages());
            System.out.println("Controller - location: " + taskRequest.getLocation());
            System.out.println("Controller - latitude: " + taskRequest.getLatitude());
            System.out.println("Controller - longitude: " + taskRequest.getLongitude());
            
            // 检查用户ID是否获取成功
            if (userId == null) {
                return error("获取用户ID失败，请重新登录");
            }
            
            // 根据用户ID查询组织ID
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null) {
            return error("请先注册组织信息");
        }
        
        // 检查组织状态
        if (!"1".equals(organization.getStatus())) {
            return error("组织信息未通过审核，无法发布任务");
        }
        
        // 创建任务对象
        DroneTask droneTask = new DroneTask();
        droneTask.setOrgId(organization.getOrgId());
        droneTask.setCategoryId(taskRequest.getCategoryId());
        droneTask.setTaskDescription(taskRequest.getTaskDescription());
        droneTask.setTaskImages(taskRequest.getTaskImages());
        
        // 设置默认值
        droneTask.setTaskTitle("测试任务 - " + new Date().getTime());
        droneTask.setTaskRequirements("请按照要求完成相关任务");
        
        // 设置地址信息（优先使用前端传来的地址信息）
        if (taskRequest.getLocation() != null && !taskRequest.getLocation().isEmpty()) {
            droneTask.setLocation(taskRequest.getLocation());
        } else {
            droneTask.setLocation("北京市朝阳区"); // 默认地址
        }
        
        // 设置经纬度（优先使用前端传来的经纬度）
        if (taskRequest.getLatitude() != null && !taskRequest.getLatitude().isEmpty()) {
            droneTask.setLatitude(new java.math.BigDecimal(taskRequest.getLatitude()));
        } else {
            droneTask.setLatitude(new java.math.BigDecimal("39.9042")); // 默认纬度
        }
        
        if (taskRequest.getLongitude() != null && !taskRequest.getLongitude().isEmpty()) {
            droneTask.setLongitude(new java.math.BigDecimal(taskRequest.getLongitude()));
        } else {
            droneTask.setLongitude(new java.math.BigDecimal("116.4074")); // 默认经度
        }
        
        droneTask.setContactPhone(phone); // 设置联系电话为当前用户的手机号
        droneTask.setStartTime(new Date());
        droneTask.setEndTime(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000L)); // 7天后
        droneTask.setBudgetMin(new java.math.BigDecimal("1000.00"));
        droneTask.setBudgetMax(new java.math.BigDecimal("5000.00"));
        droneTask.setRequiredSkills("无人机操作,航拍技术");
        droneTask.setRequiredCerts("无人机驾驶证");
        droneTask.setMaxPilots(1);
        droneTask.setStatus("1"); // 简化版直接设为已发布状态
        droneTask.setCreateBy(String.valueOf(userId));
        
        return toAjax(droneTaskService.insertDroneTask(droneTask));
        
        } catch (Exception e) {
            return error("发布任务失败: " + e.getMessage());
        }
    }

    /**
     * 简化版任务请求对象
     */
    public static class SimpleTaskRequest {
        private Long categoryId;
        private String taskDescription;
        private String taskImages;
        private String location;        // 地址名称
        private String latitude;        // 纬度
        private String longitude;       // 经度

        public Long getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(Long categoryId) {
            this.categoryId = categoryId;
        }

        public String getTaskDescription() {
            return taskDescription;
        }

        public void setTaskDescription(String taskDescription) {
            this.taskDescription = taskDescription;
        }

        public String getTaskImages() {
            return taskImages;
        }

        public void setTaskImages(String taskImages) {
            this.taskImages = taskImages;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public String getLatitude() {
            return latitude;
        }

        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }

        public String getLongitude() {
            return longitude;
        }

        public void setLongitude(String longitude) {
            this.longitude = longitude;
        }
    }
}
